<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState"
				class="ant-advanced-search-form mb-4">
			<a-row :gutter="24">
				<a-col :span="4">
					<a-form-item label="存放柜组" name="cabinetGroupId">
						<a-select
							v-model:value="searchFormState.cabinetGroupId"
							:options="cabinetGroupOptions"
							placeholder="请选择存放柜组"
							allow-clear
							@change="onChangeBioCabGroup"
						></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="存放柜子" name="cabinetInfoId">
						<a-select
							v-model:value="searchFormState.cabinetInfoId"
							:options="cabinetOptions"
							placeholder="请选择存放柜子"
							allow-clear
							@change="onChangeBioCab"
						></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="存放柜门" name="cabinetDoorId">
						<a-select
							v-model:value="searchFormState.cabinetDoorId"
							:options="cabinetDoorOptions"
							placeholder="请选择存放柜门"
							allow-clear
						></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="盘库状态" name="state">
						<a-select v-model:value="searchFormState.state" placeholder="请选择状态" allowClear>
							<a-select-option value="1">报告已生成</a-select-option>
							<a-select-option value="0">盘点中</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="盘库发起人" name="createUserName">
						<a-input v-model:value="searchFormState.createUserName" allowClear/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="盘库报告生成人" name="reportUserName">
						<a-input v-model:value="searchFormState.reportUserName" allowClear/>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="盘库创建时间" name="createTime">
						<a-range-picker v-model:value="searchFormState.createTime" value-format="YYYY-MM-DD HH:mm:ss"
										show-time/>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="盘库报告时间" name="reportTime">
						<a-range-picker v-model:value="searchFormState.reportTime" value-format="YYYY-MM-DD HH:mm:ss"
										show-time/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="table.refresh(true)">查询</a-button>
					<a-button style="margin: 0 8px" @click="() => searchFormRef.resetFields()">重置</a-button>
				</a-col>
			</a-row>
		</a-form>
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			:alert="options.alert.show"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="exportReports"
							  :loading="exportLoading"
							  v-if="hasPerm('bizInventoryCheckReportExportGoods')">
						<template #icon>
							<export-outlined/>
						</template>
						导出盘库报告
					</a-button>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'state'">
					<span v-if="record.state === 1">报告已生成</span>
					<span v-if="record.state === 0">盘点中</span>
				</template>
				<template v-if="column.dataIndex === 'cabinet'">
					<span>{{record.cabinetGroupName}} {{record.cabinetInfoName}} {{record.cabinetDoorName}}</span>
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a type="link" v-if="hasPerm(['bizInventoryCheckDetailGoods'])"
						   @click="detailRef.onOpen(record.id)">盘库明细</a>
						<a type="link" v-if="hasPerm(['bizInventoryCheckReportGoods']) && record.state === 1"
						   @click="reportRef.onOpen(record.id)">盘库报告</a>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<Detail ref="detailRef"/>
	<Report ref="reportRef"/>
</template>

<script setup name="bizinventorycheck">
	import {message} from 'ant-design-vue'
	import Detail from './detail.vue'
	import Report from './report.vue'
	import bizInventoryCheckApi from '@/api/biz/bizInventoryCheckApi'
	import bizCabinetGroupApi from '@/api/biz/bizCabinetGroupApi'
	import bizCabinetInfoApi from '@/api/biz/bizCabinetInfoApi'
	import bizCabinetDoorApi from '@/api/biz/bizCabinetDoorApi'
	//导出loading
	const exportLoading = ref(false)
	let searchFormState = reactive({})
	const searchFormRef = ref()
	const table = ref()
	const detailRef = ref()
	const reportRef = ref()
	//存放柜组
	const cabinetGroupOptions = ref([])
	//存放柜子
	const cabinetOptions = ref([])
	//存放柜门
	const cabinetDoorOptions = ref([])
	const toolConfig = {refresh: true, height: true, columnSetting: true, striped: false}
	const columns = [
		{
			title: '盘库发起时间',
			dataIndex: 'createTime'
		},
		{
			title: '盘库报告生成时间',
			dataIndex: 'reportTime'
		},
		{
			title: '盘库对象',
			dataIndex: 'cabinet'
		},
		{
			title: '系统物品数',
			dataIndex: 'curInventory'
		},
		{
			title: '盘点物品数',
			dataIndex: 'chkInventory'
		},
		{
			title: '盘点状态',
			dataIndex: 'state'
		},
		{
			title: '盘库发起人',
			dataIndex: 'createUserName'
		},
		{
			title: '盘库报告生成人',
			dataIndex: 'reportUserName'
		}
	]
	// 操作栏通过权限判断是否显示
	columns.push({
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		width: '150px'
	})
	let selectedRowKeys = ref([])
	let selectedRowData = ref([])

	// 列表选择配置
	const options = {
		alert: {
			show: false,
			clear: () => {
				selectedRowKeys = ref([])
				selectedRowData = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
				selectedRowData.value = selectedRows
			}
		}
	}
	const loadData = (parameter) => {
		const searchFormParam = JSON.parse(JSON.stringify(searchFormState))
		// createTime范围查询条件重载
		if (searchFormParam.createTime) {
			searchFormParam.startCreateTime = searchFormParam.createTime[0]
			searchFormParam.endCreateTime = searchFormParam.createTime[1]
			delete searchFormParam.createTime
		}
		// reportTime范围查询条件重载
		if (searchFormParam.reportTime) {
			searchFormParam.startReportTime = searchFormParam.reportTime[0]
			searchFormParam.endReportTime = searchFormParam.reportTime[1]
			delete searchFormParam.reportTime
		}
		return bizInventoryCheckApi.bizInventoryCheckGoodsPage(Object.assign(parameter, {
			...searchFormParam,
			goodsType: 0
		})).then((data) => {
			return data
		})
	}

	bizCabinetGroupApi.bizCabinetGroupList({}).then((res) => {
		cabinetGroupOptions.value = res.map((item) => {
			return {
				label: `${item.cabinetGroupName}-${item.cabinetGroupCode}`,
				value: item.id
			}
		})
	})

	bizCabinetInfoApi.bizCabinetList({}).then((res) => {
		cabinetOptions.value = res.map((item) => {
			return {
				label: `${item.cabinetName}`,
				value: item.id
			}
		})
	})

	bizCabinetDoorApi.bizCabinetDoorList({}).then((res) => {
		cabinetDoorOptions.value = res.map((item) => {
			return {
				label: `${item.cabinetDoorName}`,
				value: item.id
			}
		})
	})

	//存放柜组切换
	const onChangeBioCabGroup = (value) => {
		searchFormState.cabinetInfoId = undefined
		searchFormState.cabinetDoorId = undefined
		cabinetOptions.value = []
		cabinetDoorOptions.value = []
		bizCabinetInfoApi.bizCabinetList({groupId: value}).then((res) => {
			cabinetOptions.value = res.map((item) => {
				return {
					label: `${item.cabinetName}`,
					value: item.id
				}
			})
		})
	}

	//存放柜子切换
	const onChangeBioCab = (value) => {
		searchFormState.cabinetDoorId = undefined
		cabinetDoorOptions.value = []
		bizCabinetDoorApi.bizCabinetDoorList({cabinetInfoId: value}).then((res) => {
			cabinetDoorOptions.value = res.map((item) => {
				return {
					label: `${item.cabinetDoorName}`,
					value: item.id
				}
			})
		})
	}
	const exportReports = () => {
		let dataList = selectedRowData.value
		// console.log(dataList)
		if (dataList.length === 0) {
			message.warning('未选择任何记录')
			return
		}
		if (dataList.some(data => data.state === 0)) {
			// 如果记录中有未生成报告的记录，直接返回
			message.warning('部分记录未生成，报告无法导出')
			return
		} else {
			let ids = dataList.map(data => data.id)
			exportSingleReport(ids)
		}
	}

	const exportSingleReport = (ids) => {
		exportLoading.value = true
		bizInventoryCheckApi.bizInventoryCheckExport({ids, goodsType: 0}).then((res) => {
			const blob = new Blob([res.data], {type: 'application/octet-stream;charset=UTF-8'});
			const contentDisposition = res.headers['content-disposition']
			const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
			const $link = document.createElement("a");
			$link.href = URL.createObjectURL(blob);
			let reg = /^["](.*)["]$/g
			$link.download = decodeURI(patt.exec(contentDisposition)[1].replace(reg, '$1'))
			$link.click();
			document.body.appendChild($link);
			document.body.removeChild($link); // 下载完成移除元素
			window.URL.revokeObjectURL($link.href); // 释放掉blob对象
		}).finally(() => {
			exportLoading.value = false
		})
	}
</script>
